package com.share.finance.risk.rules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.common.common.Page;
import com.share.finance.risk.rules.mapper.ProjectHistMapper;
import com.share.finance.risk.rules.mapper.ProjectMapper;
import com.share.finance.risk.rules.mapper.ProjectStrategyMapper;
import com.share.finance.risk.rules.model.db.Project;
import com.share.finance.risk.rules.model.db.ProjectHist;
import com.share.finance.risk.rules.model.db.ProjectStrategy;
import com.share.finance.risk.rules.model.db.StrategyConf;
import com.share.finance.risk.rules.model.vo.ProjectHistPageReq;
import com.share.finance.risk.rules.model.vo.ProjectIdAndVersion;
import com.share.finance.risk.rules.service.IProjectHistService;
import com.share.finance.risk.rules.service.IProjectService;
import com.share.finance.risk.rules.service.IProjectStrategyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 工程表  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-12-25
 */
@Service
public class ProjectHistServiceImpl extends ServiceImpl<ProjectHistMapper, ProjectHist> implements IProjectHistService {
    @Resource
    private ProjectHistMapper projectHistMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private ProjectStrategyMapper projectStrategyMapper;
    @Resource
    private IProjectStrategyService projectStrategyService;
    @Resource
    private IProjectService projectService;

    @Override
    public Page<ProjectHist> pageList(ProjectHistPageReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        QueryWrapper<ProjectHist> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(req.getProjectId())) {
            queryWrapper.eq("project_id", req.getProjectId());
        }

        if (req.getStatus() != null) {
            queryWrapper.eq("status", req.getStatus());
        }

        if (StringUtils.isNotBlank(req.getBody())) {
            queryWrapper.like("body", req.getBody());
        }
        if (StringUtils.isNotBlank(req.getFilePath())) {
            queryWrapper.like("file_path", req.getFilePath());
        }
        if (StringUtils.isNotBlank(req.getVersion())) {
            queryWrapper.like("version", req.getVersion());
        }
        if (StringUtils.isNotBlank(req.getColumns())) {
            queryWrapper.select(req.getColumns().split(","));
        }

        List<ProjectHist> list = projectHistMapper.selectList(queryWrapper);
        Page<ProjectHist> page = new Page<>(list, new PageInfo<>(list).getTotal(), req);
        if (!CollectionUtils.isEmpty(list)) {
            //查工程
            Set<String> projectIds = list.stream().map(e -> e.getProjectId()).collect(Collectors.toSet());
            Map<String, Project> map = projectService.mapByProjectIds(projectIds);


            //查绑定
            List<ProjectIdAndVersion> projectIdAndVersionList = new LinkedList<>();
            list.stream().forEach(e -> projectIdAndVersionList.add(new ProjectIdAndVersion(e.getProjectId(), e.getVersion())));
            Map<String, List<StrategyConf>> map2 = projectStrategyService.mapByProjectIdAndVersion(projectIdAndVersionList);
            for (ProjectHist item : list) {
                Project project = map.get(item.getProjectId());
                item.setProject(project);

                List<StrategyConf> strategyConfs = map2.get(item.getProjectId() + "-" + item.getVersion());
                item.setStrategyConfs(strategyConfs);
            }
        }
        return page;
    }

    @Override
    public Map<Long, ProjectHist> mapByProjectIds(Set<Long> projectIds, Integer status) {
        Map<Long, ProjectHist> reMap = new HashMap<>();
        if (CollectionUtils.isEmpty(projectIds)) {
            return reMap;
        }

        LambdaQueryWrapper<ProjectHist> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProjectHist::getProjectId, projectIds);
        if (status != null) {
            queryWrapper.eq(ProjectHist::getStatus, status);
        }
        List<ProjectHist> list = projectHistMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(e -> reMap.put(e.getId(), e));
        }
        return reMap;
    }

    //保存版本
    @Override
    public Integer saveFlow(Long projectId, String version, List<Long> strategyIds, Boolean isAdd) {
        Date date = new Date();
        if (isAdd) {
            //新增流程
            if (StringUtils.isEmpty(version)) {
                version = System.currentTimeMillis() + "";
            } else {
                //修改流程
                List<ProjectHist> projectConfs = listByProjectIdAndVersion(projectId, version, null);
                if (!CollectionUtils.isEmpty(projectConfs)) {
                    throw new RuntimeException("版本号冲突");
                }
            }

            //新增配置
            ProjectHist conf = new ProjectHist();
            conf.setProjectId("" + projectId);
            conf.setCreateTime(date);
            conf.setVersion(version);
            conf.setStatus(0);
            projectHistMapper.insert(conf);
        } else {
            //修改流程
            Project project = projectMapper.selectById(projectId);
            if (project != null && project.getVersion().equals(version)) {
                throw new RuntimeException("默认分支无法修改");
            }

            //先删除配置
            LambdaQueryWrapper<ProjectStrategy> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(ProjectStrategy::getProjectId, projectId);
            deleteWrapper.eq(ProjectStrategy::getProjectVersion, version);
            projectStrategyMapper.delete(deleteWrapper);


            //新增配置
            ProjectHist conf = new ProjectHist();
            conf.setStatus(0);
            LambdaQueryWrapper<ProjectHist> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(ProjectHist::getProjectId, projectId);
            updateWrapper.eq(ProjectHist::getVersion, version);
            projectHistMapper.update(conf, updateWrapper);
        }

        int sort = 100;
        for (Long strategyId : strategyIds) {
            ProjectStrategy record = new ProjectStrategy();
            record.setProjectId(projectId);
            record.setProjectVersion(version);
            record.setCreateTime(date);
            record.setStrategySort(sort);
            record.setStrategyId("" + strategyId);
            projectStrategyMapper.insert(record);

            sort *= 2;
        }
        return 1;
    }

    @Override
    public List<ProjectHist> listByProjectIdAndVersion(Long projectId, String version, Integer status) {
        LambdaQueryWrapper<ProjectHist> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectHist::getProjectId, projectId);
        queryWrapper.eq(ProjectHist::getVersion, version);
        if (status != null) {
            queryWrapper.eq(ProjectHist::getStatus, status);
        }
        List<ProjectHist> list = projectHistMapper.selectList(queryWrapper);
        return list;
    }
}
